package org.autumn.aqs;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {
    public static void main(String[] args) {
        DataContainer dataContainer = new DataContainer();

        new Thread(() -> {
            dataContainer.read();

        }, "t1").start();

        new Thread(() -> {
            dataContainer.write();
        }, "t2").start();
    }
}

class DataContainer {
    int data;

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    ReentrantReadWriteLock.ReadLock r = lock.readLock();
    ReentrantReadWriteLock.WriteLock w = lock.writeLock();


    public Object read() {
        System.out.println(Thread.currentThread().getName() + "try get read lock");
        r.lock();
        System.out.println(Thread.currentThread().getName() +"get read lock");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        r.unlock();
        System.out.println(Thread.currentThread().getName() +"release read lock");
        return data;
    }

    public void write() {
        System.out.println(Thread.currentThread().getName() +"try get write lock");
        w.lock();
        System.out.println(Thread.currentThread().getName() +"get write lock");
        w.unlock();
        System.out.println(Thread.currentThread().getName() +"release write lock");
    }

}
